<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/9/17
 * Time: 9:25
 */

namespace App\Services;

use App\Exceptions\MsgException;
use App\Extensions\Exporters\PatentExporter;
use App\Extensions\Renderable\PatentDetailRenderAble;
use App\Models\Department;
use App\Patent;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;

class PatentService
{
    public function gridColumn(Grid $grid)
    {
        $user = Admin::user();
        $grid->model()->with(['fees', 'apply']);
        $grid->filter(function (Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->where(function ($query) {
                    $query->where('patent_sn', 'like', "%{$this->input}%")
                        ->orWhere('patent_name', 'like', "%{$this->input}%")
                        ->orWhere('patent_person', 'like', "%{$this->input}%")
                        ->orWhere('legal_status', 'like', "%{$this->input}%")
                        ->orWhere('applicant', 'like', "%{$this->input}%")
                        ->orWhere('inventor', 'like', "%{$this->input}%")
                        ->orWhere('publication_num', 'like', "%{$this->input}%");
                }, '关键字')->placeholder('专利号/专利名称/申请人/发明人/法律状态/公告号');
                $filter->between('apply_date', __('Apply date'))->date();
            });
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->equal('patent_type_id', '专利类型')->select(patent_type_select_option());
                $filter->between('publication_date', __('授权日'))->date();
            });
        });
        $grid->column('patent_sn', __('patent_sn'))->copyable()->style("min-width: 150px;")->filter('like');
        $grid->column('patent_name', __('专利名称'))->modal('详情', PatentDetailRenderAble::class)->filter('like');
        $grid->column('patent_type_id', __('专利类型'))->using(patent_type_select_option())->style("min-width: 100px;");
        $grid->column('is_monitor', __('年费监控'))->using(['待更新', '已监控', '已放弃'])->filter(['待更新', '已监控', '已放弃'])
            ->label(['warning', 'success', 'default'])->style("min-width: 90px;");;
        $grid->column('apply_date', __('apply_date'))->style("min-width: 100px;")->sortable();
        $grid->column('publication_num', __('公告号'))->style("min-width: 150px;");
        $grid->column('publication_date', __('授权日'))->style("min-width: 100px;");
        $grid->column('applicant', __('申请人'))->hide();
        $grid->column('inventor', __('inventor'))->hide();
        $grid->column('department.name', __('department name'))->hide();

        $grid->column('state', __('legal_status'))
            ->using([1 => '已授权', 2 => '已转化', 3 => '已受理', 4 => '失效'])
            ->label([1 => 'success', 2 => 'default', 3 => 'info', 4 => 'default'])
            ->filter([1 => '已授权', 2 => '已转化', 3 => '已受理', 4 => '失效']);

        $grid->column('score', '价值评估')->display(function ($score) {
            if ($score <= 0) {
                return '';
            }
            $url = admin_route('fjfl.show', [$this->id]);
            return <<<HTML
<a  href="{$url}"  target="_blank">
    <span style="color: #ff8a27;line-height: 20px;font-size: 1.8rem;">
        <span style="font-size: 2.4rem;">{$score}</span>分
    </span>
</a>
HTML;
        })->width(100);
        $grid->column('apply.cert', '专利证书')->display(function ($value) {
            return $value ? '下载' : '';
        })->link(function ($patent) {
            $model = $patent->apply;
            if ($model) {
                return file_custom_preview_url($model->cert, '(证书)' . $patent['patent_name']);
            }
        });
        if ($user->role_type != 1) {
            $grid->batchActions(function (BatchActions $actions) {
                $actions->disableDeleteAndHodeSelectAll();
            });
        }
        $grid->disableCreateButton();
        $grid->exporter(new PatentExporter());
        //Admin::style(' .column-patent_name a{width: 200px;word-wrap: break-word;word-break: normal;display:black}');
        return $grid;
    }

    public static function detail(Patent $patent)
    {
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($patent, function (Show $show) use ($patent) {
            $show->panel()->view('show.tab-panel');
            $show->field('patent_sn', __('Patent sn'));
            $show->field('patent_name', __('Patent name'));
            $show->field('patent_type_id', __('专利类型'))->using(patent_type_select_option());
            $show->field('department.name', __('department name'));
            $show->field('applicant', __('申请人'));
            $show->field('inventor', __('Inventor'));
            $show->field('apply_date', __('Apply date'));
            $show->field('legal_status', __('legal_status'));
            if ($model = $patent->apply) {
                $show->field('apply.charge_person', __('专利负责人'));
                $show->field('department.name', __('dept_name'));
                $show->field('apply.contact_person', __('联系人'));
                $show->field('apply.phone', __('联系电话'));
                $show->field('apply.other_applicant', __('合作申请单位'));
                if ($model['patent_type_id'] == 4) {
                    $show->field('other_patent_sn', __('国内申请号'));
                } elseif ($model['patent_type_id'] == 5) {
                    $show->field('apply.country', __('国家'));
                    $show->field('apply.apply_channel', __('途径'));
                    $show->field('apply.other_patent_sn', __('申请号'));
                }
            }
        }));
        $unpaids = $patent->unpaid();
        $paids = $patent->paid();
        if ($unpaids->first() || $paids->first()) {
            $tab->add('缴费信息', view('modal.patent-fee')->with(compact('patent', 'unpaids', 'paids')));
        }
        if ($patent->user) {
            $tab->add('负责人', Admin::show($patent->user, function (Show $show) {
                $show->panel()->view('show.tab-panel');
                $show->field('name', __('姓名'));
                $show->field('mobile', __('电话'));
                $show->field('email', __('邮箱'));
            }));
        }
        return $tab;
    }

    public function form(Form $form)
    {
        $table = $form->model()->getTable();
        $form->radio('patent_type_id', __("Patent type"))->options(patent_type_select_option())->required();
        $form->text('patent_sn', __("patent_sn"))
            ->creationRules("required|unique:$table", ['required' => '不能为空', 'unique' => '已存在不能重复'])
            ->updateRules("required|unique:$table,patent_sn,{{id}}", ['required' => '不能为空', 'unique' => '已存在不能重复']);
        $form->text('patent_name', __("patent_name"))->required();
        $form->select('department_id', __("部门"))->options(Department::departmentOptions())->required();

        $form->date('apply_date', __("apply_date"));
        $form->text('applicant', __("Applicant"));
        $form->text('inventor', __("Inventor"));
        $form->radio('state', __("legal_status"))->options([1 => '已授权', 2 => '已转化', 3 => '已受理', 4 => '失效'])->required();
        $form->saving(function (Form $form) {
            try {
                $form->patent_sn = PatentService::check_patent_sn($form->patent_sn, $form->patent_type_id);
            } catch (MsgException $exception) {
                return back()->withInput(request()->all())->withErrors([
                    'patent_sn' => $exception->getMessage()
                ]);
            }
        });
        return $form;
    }

    public static function check_patent_sn($patent_sn, $type)
    {
        if (in_array($type, [1, 2, 3])) {
            $patent_sn = china_patent_sn($patent_sn);
            if (!$patent_sn) {
                throw new MsgException('专利号错误，不符合国内专利号规则');
            }
            if (!check_patent_sn_type($patent_sn, $type)) {
                throw new MsgException('专利号与专利类型不一致');
            }
            return $patent_sn;
        }
        return $patent_sn;
    }
}
